/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mobaas.devops.ComponentFactory;
import com.mobaas.devops.Notifier;
import com.mobaas.devops.dao.NotificationDao;
import com.mobaas.devops.model.Notification;
import com.mobaas.devops.model.NotifyKind;
import com.mobaas.devops.service.NotificationService;

/**
 * 
 * @author billy zhang
 * 
 */
@Service
public class NotificationServiceImpl implements NotificationService {

	@Autowired
	private NotificationDao notiDao;
	
	@Autowired
	private ComponentFactory<Notifier> notifierFactory;
	
	@Autowired
	private ObjectMapper jsonMapper;
	
	@Override
	public void notify(NotifyKind kind, String title, String text) {
		List<Notification> list = notiDao.selectNotificationListByKind(kind.ordinal());
		for (Notification noti : list) {
			Notifier notifier = notifierFactory.getComponent(noti.getNotifier());
			try {
				Map<String, Object> config = jsonMapper.readValue(noti.getConfig(), Map.class);
				notifier.notify(title, text, config);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
